package app.common.utils.history;

import app.common.utils.FormsUtils;
import app.common.utils.IdGenerator;
import app.common.utils.YdApi;
import app.common.utils.cjt.CJtUtils;
import app.common.utils.cjt.ao.OtherDispatchCreateAo;
import com.alibaba.fastjson.JSON;
import com.aliyun.dingtalkyida_1_0.models.GetFormDataByIDResponseBody;
import com.aliyun.dingtalkyida_1_0.models.GetInstanceByIdResponseBody;
import com.gitee.feizns.dynamic.DateUtils;
import com.gitee.feizns.quickstart.jackson.JsonUtils;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Map;

interface TransferYiDaToCK {

    static void main(String[] args) {
        ckToYid("2024-01-01", "2024-01-25");
    }

    /**
     * ck,犹太人
     * @param startDate 开始日期
     * @param endDate 结束日期
     */
    static void ckToYid(String startDate, String endDate) {
        CJtUtils.resetOpenToken();
        List<String> instanceIds;
        //货品出库单传入畅捷通其他出库单
        List<String> ids = YdApi.yiDaUtils.forms.instanceIds("FORM-Q4A664A10E943MPDBSPU4AY3F4N32JOXNWJ8LH",
                startDate,
                endDate);
        for (String id : ids) {
            GetFormDataByIDResponseBody data = YdApi.yiDaUtils.forms.getById(id);
            Map<String, ?> formData = data.getFormData();
            System.out.println(JsonUtils.toJson(data));
            OtherDispatchCreateAo.Dto dto = new OtherDispatchCreateAo.Dto();
            String no = String.valueOf(formData.get("textField_l8jwp3mz"));
            String code = code(data.getModifiedTimeGMT(), no);
            dto.setExternalCode(code + "-" + no);
            dto.setCode(code);
            dto.setVoucherType(new OtherDispatchCreateAo.Dto.VoucherType("ST1024"));
            dto.setVoucherDate(data.getModifiedTimeGMT());
            dto.setBusiType(new OtherDispatchCreateAo.Dto.BusiType("13"));
            dto.setWarehouse(new OtherDispatchCreateAo.Dto.Warehouse(String.valueOf(formData.get("textField_l8jwp3n3"))));
            dto.setMemo(
                    String.format("来源=[宜搭] 表单=[%s] 单号=[%s] 备注：[%s] 原单号：[%s]",
                            formData.get("textField_lg0ibky2"),
                            code,
                            formData.get("textField_l8jwsgqf"),
                            formData.get("textField_ljjgry4w")
                    )
            );
            OtherDispatchCreateAo.Dto.RDRecordDetails details = new OtherDispatchCreateAo.Dto.RDRecordDetails();
            details.setInventory(new OtherDispatchCreateAo.Dto.RDRecordDetails.Inventory(String.valueOf(formData.get("textField_l8jwp3mz"))));
            double baseQuantity = Double.parseDouble(String.valueOf(formData.get("numberField_l8jwp3n1")));
            details.setBaseQuantity(BigDecimal.valueOf(baseQuantity));
            BigDecimal price = FormsUtils.getPrice(no);
            details.setPrice(price);
            details.setAmount(price.multiply(new BigDecimal(baseQuantity)));
            dto.setRDRecordDetailsObj(details);
            try {
                CJtUtils.otherDispatchCreate(dto);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

        //生产一部报工
        instanceIds = YdApi.yiDaUtils.processes.getIds("FORM-GC9664C19UV8SVZJ8Z0M3B3PSCB53GIQWHGFLV", req -> {
            req.setModifiedFromTimeGMT(startDate);
            req.setModifiedToTimeGMT(endDate);
            req.setInstanceStatus("COMPLETED");
            req.setApprovedResult("agree");
        });
        for (String instanceId : instanceIds) {
            GetInstanceByIdResponseBody instance = YdApi.yiDaUtils.processes.getById(instanceId);
            Map<String, ?> data = instance.getData();
            System.out.println(JSON.toJSONString(instance));
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> o = (List<Map<String, Object>>) data.get("tableField_l4xj70qy");
            if ( o != null && !o.isEmpty() ) {
                for (Map<String, Object> map : o) {
                    OtherDispatchCreateAo.Dto dto = new OtherDispatchCreateAo.Dto();
                    String no = String.valueOf(map.get("textField_le25hjve"));
                    String code = code(instance.getModifiedTimeGMT(), no);
                    dto.setExternalCode(code + "-" + no);
                    dto.setCode(code);
                    dto.setVoucherType(new OtherDispatchCreateAo.Dto.VoucherType("ST1024"));
                    dto.setVoucherDate(instance.getModifiedTimeGMT());
                    dto.setBusiType(new OtherDispatchCreateAo.Dto.BusiType("13"));
                    dto.setWarehouse(new OtherDispatchCreateAo.Dto.Warehouse("038"));
                    dto.setMemo(
                            String.format("来源=[宜搭-生产一部报工] 表单=[%s] 单号=[%s] 备注：[%s] 原单号：[%s]",
                                    "生产一部报工",
                                    code,
                                    data.get("textField_l5dhqcrf"),
                                    data.get("textField_lfbzclcz"))
                    );
                    OtherDispatchCreateAo.Dto.RDRecordDetails detail = new OtherDispatchCreateAo.Dto.RDRecordDetails();
                    detail.setInventory(new OtherDispatchCreateAo.Dto.RDRecordDetails.Inventory(String.valueOf(no)));
                    double baseQuantity = Double.parseDouble(String.valueOf(map.get("numberField_lbczptiu")));
                    detail.setBaseQuantity(BigDecimal.valueOf(baseQuantity));
                    BigDecimal price = FormsUtils.getPrice(no);
                    detail.setPrice(price);
                    detail.setAmount(price.multiply(new BigDecimal(baseQuantity)));
                    dto.setRDRecordDetailsObj(detail);
                    try {
                        CJtUtils.otherDispatchCreate(dto);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }

        }

        //生产二部报工
        instanceIds = YdApi.yiDaUtils.processes.getIds("FORM-Z2666J810PK2TK7J6G5425QYSMYE2RB2UC66LW4", req -> {
            req.setModifiedFromTimeGMT(startDate);
            req.setModifiedToTimeGMT(endDate);
            req.setInstanceStatus("COMPLETED");
            req.setApprovedResult("agree");
        });
        for (String instanceId : instanceIds) {
            GetInstanceByIdResponseBody instance = YdApi.yiDaUtils.processes.getById(instanceId);
            Map<String, ?> data = instance.getData();
            System.out.println(JSON.toJSONString(instance));
            //详情
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> o = (List<Map<String, Object>>) data.get("tableField_l4xj70qy");
            if ( o != null && !o.isEmpty() ) {
                for (Map<String, Object> map : o) {
                    OtherDispatchCreateAo.Dto dto = new OtherDispatchCreateAo.Dto();
                    String no = String.valueOf(map.get("textField_le25hjve"));
                    String code = code(instance.getModifiedTimeGMT(), no);
                    dto.setExternalCode(code + "-" + no);
                    dto.setCode(code);
                    dto.setVoucherType(new OtherDispatchCreateAo.Dto.VoucherType("ST1024"));
                    dto.setVoucherDate(instance.getModifiedTimeGMT());
                    dto.setBusiType(new OtherDispatchCreateAo.Dto.BusiType("13"));
                    dto.setWarehouse(new OtherDispatchCreateAo.Dto.Warehouse("038"));
                    dto.setMemo(
                            String.format("来源=[宜搭-生产二部报工] 表单=[%s] 单号=[%s] 备注：[%s] 原单号：[%s]",
                                    "生产二部报工",
                                    code,
                                    data.get("textField_l5dhqcrf"),
                                    data.get("textField_lfbzclcz"))
                    );
                    OtherDispatchCreateAo.Dto.RDRecordDetails detail = new OtherDispatchCreateAo.Dto.RDRecordDetails();
                    detail.setInventory(new OtherDispatchCreateAo.Dto.RDRecordDetails.Inventory(String.valueOf(no)));
                    double baseQuantity = Double.parseDouble(String.valueOf(map.get("numberField_lbczptiu")));
                    detail.setBaseQuantity(BigDecimal.valueOf(baseQuantity));
                    BigDecimal price = FormsUtils.getPrice(no);
                    detail.setPrice(price);
                    detail.setAmount(price.multiply(new BigDecimal(baseQuantity)));
                    dto.setRDRecordDetailsObj(detail);
                    try {
                        CJtUtils.otherDispatchCreate(dto);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }

        //生产领料出库
        instanceIds = YdApi.yiDaUtils.processes.getIds("FORM-Z2666J810PK2TK7J6G5425QYSMYE2RB2UC66LU4", req -> {
            req.setModifiedFromTimeGMT(startDate);
            req.setModifiedToTimeGMT(endDate);
            req.setInstanceStatus("COMPLETED");
            req.setApprovedResult("agree");
        });

        for (String id : instanceIds) {
            GetInstanceByIdResponseBody instance = YdApi.yiDaUtils.processes.getById(id);
            Map<String, ?> data = instance.getData();
            @SuppressWarnings("unchecked")
            List<Map<String, Object>> o = (List<Map<String, Object>>) data.get("tableField_l57i1a1x");
            for (Map<String, Object> map : o) {
                double baseQuantity = Double.parseDouble(String.valueOf(map.get("numberField_l57i1a1z")));
                if ( baseQuantity <= 0.00001 )
                    return;
                OtherDispatchCreateAo.Dto dto = new OtherDispatchCreateAo.Dto();
                String no = String.valueOf(map.get("textField_l5di70a1"));
                String code = code(instance.getModifiedTimeGMT(), no);
                dto.setExternalCode(code + "-" + no);
                dto.setCode(code);
                dto.setVoucherType(new OtherDispatchCreateAo.Dto.VoucherType("ST1024"));
                dto.setVoucherDate(instance.getModifiedTimeGMT());
                dto.setBusiType(new OtherDispatchCreateAo.Dto.BusiType("13"));
                dto.setWarehouse(new OtherDispatchCreateAo.Dto.Warehouse("028"));
                dto.setMemo(
                        String.format("来源=[宜搭] 表单=[%s] 单号=[%s] 备注：[%s] 原单号：[%s]",
                                "生产领料",
                                code,
                                "领料出库",
                                data.get("serialNumberField_lg7ok4i2"))
                );
                OtherDispatchCreateAo.Dto.RDRecordDetails detail = new OtherDispatchCreateAo.Dto.RDRecordDetails();
                detail.setInventory(new OtherDispatchCreateAo.Dto.RDRecordDetails.Inventory(String.valueOf(no)));
                detail.setBaseQuantity(BigDecimal.valueOf(baseQuantity));
                BigDecimal price = FormsUtils.getPrice(no);
                detail.setPrice(price);
                detail.setAmount(price.multiply(new BigDecimal(baseQuantity)));
                dto.setRDRecordDetailsObj(detail);
                try {
                    CJtUtils.otherDispatchCreate(dto);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 编号发电机
     */
    IdGenerator idGenerator = new IdGenerator();

    /**
     * 代码
     * @param date 日期
     * @param no 没有
     * @return {@link String}
     */
    static String code(String date, String no) {
        LocalDateTime time = DateUtils.parse(date, LocalDateTime.class);
        String key = no + "-" + time;
        return String.format("CK%s%05d", DateUtils.format(time, "yyyyMMddHHmm"), idGenerator.next(key));
    }


}